/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-03     ThinkPad       the first version
 */
#include <ComApp4.h>
#include <rtthread.h>
#include <rtdevice.h>
#include "drv_common.h"
#include <dfs_posix.h>
#include <../utils/cJSON.h>
#include <ConfigInit.h>

#define POOL_SIZE_4 (700)

static char* SAMPLE_UART_NAME = "uart6";
static rt_thread_t thread;


static int s_dlRecv = 0;
static rt_uint8_t s_head1 = 0;
static rt_uint8_t s_head2 = 0;
static rt_uint8_t s_head3 = 0;

static rt_uint8_t s_pool[POOL_SIZE_4] = {0};
static int s_nDataIndex = 0;

#define BUF_SIZE_4 (350)
static rt_uint8_t s_buf[BUF_SIZE_4] = {0};



/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
rt_device_t serial4;
static struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;  /* 初始化配置参数 */

/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}


static int parse(rt_uint8_t* buf)
{
    for (int i=0; i<s_nDataIndex-2; ++i)
    {
        if (buf[i]==s_head1 && buf[i+1]==s_head2 && buf[i+2]==s_head3)
        {
            if (i+s_dlRecv > s_nDataIndex)  // data is not ready, wait for more data
            {
                return i;
            }
            else
            {
                memcpy(s_buf, buf+i, s_dlRecv);
                return i+s_dlRecv;
            }
        }
    }

    return s_nDataIndex-3;  // in case of bytes like ........head1 head2
}

static void serial_thread_entry(void *parameter)
{
    rt_uint8_t ch;
    //char str[] = "hello\r\n";

    while (1)
    {

        // extern rt_device_t serial3;
        // char str[] = "hello RT-Thread from 4 to 3\r\n";
        // rt_thread_mdelay(20);
        // rt_device_write(serial3, 0, str, (sizeof(str) - 1));
        // continue;


        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial4, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        /* 读取到的数据通过串口错位输出 */
//        ch = ch + 2;
//        rt_device_write(serial4, 0, &ch, 1);
//        rt_device_write(serial4, 0, str, (sizeof(str) - 1));
//        rt_thread_mdelay(200);

        s_pool[s_nDataIndex++] = ch;
        if (s_nDataIndex >= s_dlRecv)
        {
            int nMove = parse(s_pool);
            if (nMove > 0)
            {
                memmove(s_pool, s_pool+nMove, s_nDataIndex-nMove);
                s_nDataIndex -= nMove;
            }
        }

    }
}


int copyData4(rt_uint8_t* dst)
{
    memcpy(dst, s_buf, s_dlRecv);
    return s_dlRecv;
}


int ComApp4()
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
//    char str[] = "hello RT-Thread!\r\n";

    rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);

    /* step1：查找串口设备 */
    serial4 = rt_device_find(uart_name);

    if (RT_NULL == serial4)
    {
        rt_kprintf("\nopen com4 failed\n");
    }
    else {
        rt_kprintf("\nopen com4 ok\n");
    }


    cJSON* root = getComConfigRoot();
    cJSON* myComInfo = cJSON_GetArrayItem(root, 3);
    int nBaudRate = cJSON_GetObjectItem(myComInfo, "baudrate")->valueint;
    int nParity = cJSON_GetObjectItem(myComInfo, "parity")->valueint;

    s_dlRecv = cJSON_GetObjectItem(myComInfo, "dl_recv")->valueint;
    s_head1 = cJSON_GetObjectItem(myComInfo, "head_1")->valueint;
    s_head2 = cJSON_GetObjectItem(myComInfo, "head_2")->valueint;
    s_head3 = cJSON_GetObjectItem(myComInfo, "head_3")->valueint;



    /* step2：修改串口配置参数 */
    config.baud_rate = nBaudRate;      //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
    config.parity    = nParity;           //无奇偶校验位

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial4, RT_DEVICE_CTRL_CONFIG, &config);

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial4, RT_DEVICE_FLAG_TX_BLOCKING|RT_DEVICE_FLAG_RX_NON_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial4, uart_input);
    /* 发送字符串 */
//    rt_device_write(serial4, 0, str, (sizeof(str) - 1));

    /* 创建 serial4 线程 */
    thread = rt_thread_create("tCom4", serial_thread_entry, RT_NULL, 1024, 25, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_kprintf("start com4 thread ok\n");
        rt_thread_startup(thread);
    }
    else
    {
        rt_kprintf("start com4 thread failed\n");
        ret = RT_ERROR;
    }


    return ret;
}




void restartComApp4()
{
    rt_device_close(serial4);
    rt_thread_delete(thread);


    cJSON* root = getComConfigRoot();
    cJSON* myComInfo = cJSON_GetArrayItem(root, 3);
    int nBaudRate = cJSON_GetObjectItem(myComInfo, "baudrate")->valueint;
    int nParity = cJSON_GetObjectItem(myComInfo, "parity")->valueint;

    /* step2：修改串口配置参数 */
    config.baud_rate = nBaudRate;      //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
    config.parity    = nParity;           //无奇偶校验位


//    /* step2：修改串口配置参数 */
//    config.baud_rate = nBaudRate;      //修改波特率为 9600
//    config.data_bits = nDatabit;           //数据位 8
//    config.stop_bits = nStopbit;           //停止位 1
//    config.rx_bufsz  = 512;                   //修改缓冲区 buff size 为 128
//    config.parity    = nParity;           //无奇偶校验位

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(serial4, RT_DEVICE_CTRL_CONFIG, &config);

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial4, RT_DEVICE_FLAG_TX_BLOCKING|RT_DEVICE_FLAG_RX_NON_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial4, uart_input);



    thread = rt_thread_create("tCom4", serial_thread_entry, RT_NULL, 1024, 25, 10);
        /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_kprintf("start com3 thread ok\n");
        rt_thread_startup(thread);
    }
    else
    {
        rt_kprintf("start com3 thread failed\n");
    }
}




